package com.fly.visit.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import com.fly.core.JsonResult;
import com.fly.visit.entity.Article;
import com.fly.visit.service.WebVisitorSevice;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api(tags = "WebApi接口")
@RequestMapping("/api")
@ConditionalOnWebApplication
public class ApiController
{
    @Autowired
    WebClient webClient;
    
    @Autowired
    WebVisitorSevice webVisitorSevice;
    
    @ApiOperation("新增Article")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParam(name = "url", value = "文章地址", required = true)
    @PostMapping("/addNew")
    public JsonResult<?> addNew(String url)
    {
        log.info("start add...");
        if (url.contains("?"))
        {
            url = StringUtils.substringBefore(url, "?");
        }
        String response = webClient.get().uri(url).acceptCharset(StandardCharsets.UTF_8).retrieve().bodyToMono(String.class).timeout(Duration.ofSeconds(10)).block();
        String title = StringUtils.substringBetween(response, "<title>", "-CSDN博客</title>");
        if (!StringUtils.equals(title, "404"))
        {
            String articleId = StringUtils.substringAfter(url, "details/");
            Article article = new Article().setArticleId(NumberUtils.toLong(articleId)).setTitle(title).setViewCount(0L).setUrl(url);
            webVisitorSevice.addNew(article);
            return JsonResult.success(article);
        }
        return JsonResult.error("addNew failed");
    }
    
    @ApiOperation("查看articles")
    @ApiOperationSupport(order = 20)
    @GetMapping("/view")
    public JsonResult<?> view()
    {
        return JsonResult.success(webVisitorSevice.getArticles());
    }
    
    @ApiOperation("保存序列化")
    @ApiOperationSupport(order = 30)
    @GetMapping("/serialization/save")
    public JsonResult<?> saveSer()
        throws Exception
    {
        File file = new File("/data/articles.ser");
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)))
        {
            oos.writeObject(webVisitorSevice.getArticles());
        }
        return JsonResult.success().setMessage("保存序列化成功");
    }
    
    @ApiOperation("删除序列化")
    @ApiOperationSupport(order = 40)
    @GetMapping("/serialization/delete")
    public JsonResult<?> delSer()
    {
        File file = new File("/data/articles.ser");
        FileUtils.deleteQuietly(file);
        return JsonResult.success().setMessage("删除序列化成功");
    }
}
